<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>付款计划表生成器</title>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --accent-color: #4895ef;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --success-color: #4cc9f0;
            --border-radius: 6px;
            --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.5;
            color: var(--dark-color);
            background-color: #fff;
        }
        
        .form-container {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-bottom: 10px;
            align-items: center;
            border: 1px solid #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4), 0 0 50px rgba(0, 0, 0, 0.15) inset, 0 0 15px rgba(255, 255, 255, 0.6) inset;
        }
        
        .form-group {
            display: flex;
            align-items: center;
        }
        
        label {
            font-weight: 600;
            color: var(--dark-color);
            margin-right: 8px;
            white-space: nowrap;
        }
        
        input, select {
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: var(--border-radius);
            font-size: 14px;
            transition: border-color 0.3s;
            width: 120px;
        }
        
        input:focus, select:focus {
            outline: none;
            border-color: var(--accent-color);
        }
        
        button {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 600;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: var(--secondary-color);
        }
        
        .error {
            color: #dc3545;
            margin: 10px 0;
            padding: 8px;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: var(--border-radius);
            display: none;
        }
        
        .table-container {
            overflow-x: auto;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            background-color: white;
            margin-top: 20px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        
        th, td {
            border: 1px solid #dee2e6;
            padding: 10px;
            text-align: center;
        }
        
        th {
            background-color: var(--primary-color);
            color: white;
            font-weight: 600;
            position: sticky;
            top: 0;
        }
        
        tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        tr:hover {
            background-color: #e9ecef;
        }
        
        input.editable {
            width: 80px;
            padding: 5px;
            text-align: center;
        }
        
        .highlight {
            background-color: rgba(72, 149, 239, 0.1);
            font-weight: 600;
        }
        
        @media (max-width: 768px) {
            .form-container {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .form-group {
                width: 100%;
            }
            
            input, select {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-group">
            <label for="totalAmount">总金额(含税):</label>
            <input type="number" id="totalAmount" step="0.01" min="0" placeholder="总金额">
        </div>
        
        <div class="form-group">
            <label for="months">付款月数:</label>
            <input type="number" id="months" min="1" value="12" placeholder="月数">
        </div>
        
        <div class="form-group">
            <label for="startYear">开始年:</label>
            <select id="startYear"></select>
        </div>
        
        <div class="form-group">
            <label for="startMonth">开始月:</label>
            <select id="startMonth">
                <option value="1">1月</option>
                <option value="2">2月</option>
                <option value="3">3月</option>
                <option value="4">4月</option>
                <option value="5">5月</option>
                <option value="6">6月</option>
                <option value="7">7月</option>
                <option value="8">8月</option>
                <option value="9">9月</option>
                <option value="10">10月</option>
                <option value="11">11月</option>
                <option value="12">12月</option>
            </select>
        </div>
        
        <div class="form-group">
            <label for="taxRate">税率(%):</label>
            <input type="number" id="taxRate" step="0.01" min="0" value="13" placeholder="税率">
        </div>
        
        <div class="form-group">
            <label for="unitPrice">单价(不含税):</label>
            <input type="number" id="unitPrice" step="0.01" min="0" placeholder="单价">
        </div>
        
        <div class="form-group"><button id="generateBtn">生成计划表</button></div>
    </div>
    
    <div id="error" class="error"></div>
    
    <div id="paymentPlan"></div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化年份选择
            const startYearSelect = document.getElementById('startYear');
            const currentYear = new Date().getFullYear();
            for (let year = currentYear - 2; year <= currentYear + 3; year++) {
                const option = document.createElement('option');
                option.value = year;
                option.textContent = year;
                if (year === currentYear) {
                    option.selected = true;
                }
                startYearSelect.appendChild(option);
            }
            
            // 获取每月工作日数的函数
            function getWorkingDays(year, month) {
                // 默认每月22个工作日，2月20个
                return month === 2 ? 20 : 22;
            }
            
            // 均匀分配人天数到各月（返回整数数组）
            function distributeEvenly(total, parts) {
                const base = Math.floor(total / parts);
                const remainder = total % parts;
                const result = Array(parts).fill(base);
                
                for (let i = 0; i < remainder; i++) {
                    result[i]++;
                }
                
                return result;
            }
            
            // 更新行数据
            function updateRow(row, unitPrice, taxRate) {
                const workingDays = parseInt(row.querySelector('.working-days').value) || 0;
                const manDays = parseInt(row.querySelector('.man-days').value) || 0;
                
                // 计算人数（保留整数）
                const people = manDays > 0 ? Math.round(manDays / workingDays) : 0;
                row.querySelector('.people').textContent = people;
                
                // 计算金额
                const paymentSubtotal = unitPrice * manDays;
                const paymentTax = paymentSubtotal * (taxRate / 100);
                const payment = paymentSubtotal + paymentTax;
                
                row.querySelector('.payment-subtotal').textContent = paymentSubtotal.toFixed(2);
                row.querySelector('.payment-tax').textContent = paymentTax.toFixed(2);
                row.querySelector('.payment').textContent = payment.toFixed(2);
                
                // 重新计算总计
                calculateTotals(unitPrice, taxRate);
            }
            
            // 计算总计
            function calculateTotals(unitPrice, taxRate) {
                const rows = document.querySelectorAll('#paymentTable tbody tr:not(.highlight)');
                let totalManDays = 0;
                let totalPayment = 0;
                let totalSubtotal = 0;
                let totalTax = 0;
                
                rows.forEach(row => {
                    totalManDays += parseInt(row.querySelector('.man-days').value) || 0;
                    totalPayment += parseFloat(row.querySelector('.payment').textContent) || 0;
                    totalSubtotal += parseFloat(row.querySelector('.payment-subtotal').textContent) || 0;
                    totalTax += parseFloat(row.querySelector('.payment-tax').textContent) || 0;
                });
                
                // 更新总计行
                const totalRow = document.querySelector('#paymentTable tbody tr.highlight');
                if (totalRow) {
                    totalRow.querySelector('td:nth-child(2)').textContent = totalManDays;
                    totalRow.querySelector('td:nth-child(4)').textContent = totalPayment.toFixed(2);
                    totalRow.querySelector('td:nth-child(5)').textContent = totalSubtotal.toFixed(2);
                    totalRow.querySelector('td:nth-child(6)').textContent = totalTax.toFixed(2);
                }
            }
            
            function generatePaymentPlan() {
                // 获取输入值
                const totalAmount = parseFloat(document.getElementById('totalAmount').value);
                const months = parseInt(document.getElementById('months').value);
                const startYear = parseInt(document.getElementById('startYear').value);
                const startMonth = parseInt(document.getElementById('startMonth').value);
                const taxRate = parseFloat(document.getElementById('taxRate').value);
                const unitPrice = parseFloat(document.getElementById('unitPrice').value);
                
                // 验证输入
                const errorElement = document.getElementById('error');
                errorElement.style.display = 'none';
                
                if (isNaN(totalAmount)) {
                    showError("请输入付款总金额");
                    return;
                }
                if (isNaN(months) || months <= 0) {
                    showError("请输入有效的付款月数");
                    return;
                }
                if (isNaN(taxRate) || taxRate < 0) {
                    showError("请输入有效的税率");
                    return;
                }
                if (isNaN(unitPrice) || unitPrice <= 0) {
                    showError("请输入有效的单价");
                    return;
                }
                
                // 计算不含税金额和合计人天
                const subtotal = totalAmount / (1 + taxRate / 100);
                const quantity = Math.round(subtotal / unitPrice);
                
                // 计算每月平均人天（整数分配）
                const monthlyManDays = distributeEvenly(quantity, months);
                
                // 生成付款计划表
                let tableHTML = `
                    <div class="table-container">
                        <table id="paymentTable">
                            <thead>
                                <tr>
                                    <th>期数</th>
                                    <th>付款年月</th>
                                    <th>当月工作日</th>
                                    <th>工作量(人天)</th>
                                    <th>人数</th>
                                    <th>付款金额(含税)</th>
                                    <th>不含税金额</th>
                                    <th>税额</th>
                                    <th>备注</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                let currentYear = startYear;
                let currentMonth = startMonth - 1;
                
                for (let i = 1; i <= months; i++) {
                    currentMonth++;
                    if (currentMonth > 12) {
                        currentMonth = 1;
                        currentYear++;
                    }
                    
                    const monthName = `${currentYear}年${currentMonth}月`;
                    const workingDays = getWorkingDays(currentYear, currentMonth);
                    const manDays = monthlyManDays[i-1];
                    const people = manDays > 0 ? Math.round(manDays / workingDays) : 0;
                    
                    // 计算金额
                    const paymentSubtotal = unitPrice * manDays;
                    const paymentTax = paymentSubtotal * (taxRate / 100);
                    const payment = paymentSubtotal + paymentTax;
                    
                    tableHTML += `
                        <tr>
                            <td>${i}/${months}</td>
                            <td>${monthName}</td>
                            <td><input type="number" class="editable working-days" value="${workingDays}" min="0"></td>
                            <td><input type="number" class="editable man-days" value="${manDays}" min="0"></td>
                            <td class="people">${people}</td>
                            <td class="payment">${payment.toFixed(2)}</td>
                            <td class="payment-subtotal">${paymentSubtotal.toFixed(2)}</td>
                            <td class="payment-tax">${paymentTax.toFixed(2)}</td>
                            <td></td>
                        </tr>
                    `;
                }
                
                // 添加总计行
                tableHTML += `
                        <tr class="highlight">
                            <td colspan="3">总计</td>
                            <td>${quantity}</td>
                            <td></td>
                            <td>${totalAmount.toFixed(2)}</td>
                            <td>${subtotal.toFixed(2)}</td>
                            <td>${(totalAmount - subtotal).toFixed(2)}</td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
                </div>
                `;
                
                document.getElementById('paymentPlan').innerHTML = tableHTML;
                
                // 为动态生成的输入框添加事件监听器
                document.querySelectorAll('.working-days, .man-days').forEach(input => {
                    input.addEventListener('change', function() {
                        const row = this.closest('tr');
                        updateRow(row, unitPrice, taxRate);
                    });
                    
                    // 添加输入时实时更新
                    input.addEventListener('input', function() {
                        const row = this.closest('tr');
                        updateRow(row, unitPrice, taxRate);
                    });
                });
            }
            
            function showError(message) {
                const errorElement = document.getElementById('error');
                errorElement.textContent = message;
                errorElement.style.display = 'block';
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            }
            
            // 使用事件监听器
            document.getElementById('generateBtn').addEventListener('click', generatePaymentPlan);
        });
    </script>
</body>
</html>